# flask web 网络编程文件
from flask import Flask, render_template,request,escape
from functools import wraps
from flask import Flask, request, render_template, redirect, url_for, flash, session

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import and_, or_
from vsearch import search4letters
import requests,json
import baidu_skin_name

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.secret_key = '\xc9ixnRb\xe40\xd4\xa5\x7f\x03\xd0y6\x01\x1f\x96\xeao+\x8a\x9f\xe4'

db = SQLAlchemy(app)

# 定义ORM
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    password = db.Column(db.String(80))
    email = db.Column(db.String(120), unique=True)

    def __repr__(self):
        return '<User %r>' % self.username


def results(args):
    pass


def results(args):
    pass


def results(args):
    pass


def results(args):
    pass


def results(args):
    pass


def results(args):
    pass


@app.before_first_request
def create_db():
    db.drop_all()  # 每次运行，先删除再创建
    db.create_all()

    admin = User(username='admin', password='root', email='admin@example.com')
    db.session.add(admin)

    guestes = [User(username='guest1', password='guest1', email='guest1@example.com'),
               User(username='guest2', password='guest2', email='guest2@example.com'),
               User(username='guest3', password='guest3', email='guest3@example.com'),
               User(username='guest4', password='guest4', email='guest4@example.com')]
    db.session.add_all(guestes)
    db.session.commit()

# 登录检验（用户名、密码验证）
def valid_login(username, password):
    user = User.query.filter(and_(User.username == username, User.password == password)).first()
    if user:
        return True
    else:
        return False


# 注册检验（用户名、邮箱验证）
def valid_regist(username, email):
    user = User.query.filter(or_(User.username == username, User.email == email)).first()
    if user:
        return False
    else:
        return True

# 登录
def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # if g.user:
        if session.get('username'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('login', next=request.url)) #
    return wrapper


# 1.主页
@app.route('/')
def home():
    return render_template('home.html', username=session.get('username'))


# 2.登录
@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'], request.form['password']):
            flash("成功登录！")
            session['username'] = request.form.get('username')
            return redirect(url_for('home'))
        else:
            error = '错误的用户名或密码！'

    return render_template('login.html', error=error)


# 3.注销
@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('home'))


# 4.注册
@app.route('/regist', methods=['GET', 'POST'])
def regist():
    error = None
    if request.method == 'POST':
        if request.form['password1'] != request.form['password2']:
            error = '两次密码不相同！'
        elif valid_regist(request.form['username'], request.form['email']):
            user = User(username=request.form['username'], password=request.form['password1'],
                        email=request.form['email'])
            db.session.add(user)
            db.session.commit()

            flash("成功注册！")
            return redirect(url_for('login'))
        else:
            error = '该用户名或邮箱已被注册！'

    return render_template('regist.html', error=error)


# 5.个人中心
@app.route('/panel')
@login_required
def panel():
    username = session.get('username')
    user = User.query.filter(User.username == username).first()
    return render_template("panel.html", user=user)


@app.route('/search4', methods=['POST'])
# 这些数据来自哪里？
def do_search() -> 'html':
    image = request.form['image']
    title = '这是你的结果：'
    # df = request.form['df']
    # face = request.form['face']
    # dou = request.form['dou']
    # zhi = request.form['zhi']
    # ban = request.form['ban']
    # zhouwen = request.form['zhouwen']
    df = baidu_skin_name.skin_test(image)
    face = baidu_skin_name.face_num(image)
    dou = baidu_skin_name.dou_num(image)
    zhi = baidu_skin_name.zhi_num(image)
    ban = baidu_skin_name.ban_num(image)
    zhouwen = baidu_skin_name.zhou_num(image)
    # results = df.loc[:, ['number', 'number_of_blain', 'number_of_speckle','number_of_nevus','number_of_wrinkle']]
    # results.columns = ['人脸数量', '痘痘数量', '斑数量','痣数量','皱纹数量']


    # 日志请求信息，存档在vsearch.log中
#     my_results = request.form,request.remote_addr,request.user_agent
    my_results =request
    print(request.form,request.remote_addr,request.user_agent)
    # results=str(search4letters(phrase,letters))
    with open('vsearch.log','a')as f:
        req = str(dir(request))
        print(request.form,request.remote_addr,request.user_agent,results,sep='|',file=f)
    

    return render_template('results.html',
                           the_title=title,
                           # the_results=results,
                           the_req = req,
                           # my_results = my_results,
                           the_num = face,
                           the_df = df,
                           the_dou = dou,
                           the_zhi = zhi,
                           the_ban = ban,
                           the_zhouwen = zhouwen)

@app.route('/main')
def main():
    title = '欢迎来到vicky的测试站主页'
    return render_template('main.html', username=session.get('username'),the_title=title)

@app.route('/first')
def first_page() -> 'html':
    title = '欢迎来到vicky的皮肤测试站'
    return render_template('first.html',
                            the_title=title)


#用户日志的管理页面
@app.route('/viewlog')
def view_the_log() ->'html':
    '''Display the contents of the log file as a HTML table.'''
    contents = []
    with open('vsearch.log','r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))

    len(contents)
    titles = ('用户提交','Remote_addr','代理商','Result')
    return  render_template('viewlog.html',
                            the_title ='日志系统后台',
                            the_data = contents)



# @app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    title = '欢迎来到vicky的皮肤测试站'
    # image = request.form['image']
    # df = baidu_skin_name.skin_test(image)
    # face = baidu_skin_name.face_num(image)
    # dou = baidu_skin_name.dou_num(image)
    # zhi = baidu_skin_name.zhi_num(image)
    # ban = baidu_skin_name.ban_num(image)
    # zhouwen = baidu_skin_name.zhou_num(image)
    # # results = df.loc[:, ['number', 'number_of_blain', 'number_of_speckle','number_of_nevus','number_of_wrinkle']]
    # # results.columns = ['人脸数量', '痘痘数量', '斑数量','痣数量','皱纹数量']

    return render_template('entry.html')
                           # the_title=title,
                           # the_image = image,
                           # the_num = face,
                           # the_df = df,
                           # the_dou = dou,
                           # the_zhi = zhi,
                           # the_ban = ban,
                           # the_zhouwen = zhouwen)


if __name__ == '__main__':
    app.run(debug=True)
